<?php
/**
 * 系统国家
 * (model)
 */

namespace App\Models\Basics;

use Illuminate\Database\Eloquent\Model;
class SysCountry extends Model
{
    protected $table = 'b_sys_country';

    public $timestamps = false;

    protected $guarded = [];

    const EU_COUNTRY_ID = 20;
    const JP_COUNTRY_ID = 12; //jp国家
    const UK_COUNTRY_ID = 3; //uk国家

    public static function options()
    {
        return self::query()->pluck('country','id');
    }

    public static function getCountryById($id){
        return self::query()->where('id',$id)->value('country');
    }

    public static function getIdByCountry($country){
        if($country == 'GB') $country = 'UK';
        return self::query()->where('country',$country)->value('id');
    }

    public static function getCountryByCountryIds($ids){
        return self::query()->whereIn('id',$ids)->pluck('country','id');
    }

    /**
     * 获取模型
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getModelById($id){
        return self::query()->where('id',$id)->first();
    }

    /**
     * 获取模型字段
     * @param $id
     * @param $field
     * @return mixed
     */
    public static function getValueById($id,$field){
        return self::query()->where('id',$id)->value($field);
    }

    /**
     * 获取Amazon国家对应的站点id
     * @param $countryId
     * @return int|mixed
     */
    public static function getAreaIdByCountryId($countryId){
        return SysICountry::getAreaIdByCountryId($countryId);
    }
    /**
     * 获取对应站点下的库存国家id
     * @param $areaId
     * @return int|mixed
     */
    public static function getCountryIdsByAreaId($areaId){
        return SysICountry::getCountryIdsByAreaId($areaId);
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            $count = AmazonCountry::query()->where('country_id',$model->id)->count();
            if($count > 0){
                throw new \Exception('使用中勿删除');
            }
            $count = SysICountry::query()->where('country_id',$model->id)->count();
            if($count > 0){
                throw new \Exception('使用中勿删除');
            }
        });
    }
}
